import { component$ } from "@builder.io/qwik";
import type { DocumentHead } from "@builder.io/qwik-city";
import { routeLoader$, z } from "@builder.io/qwik-city";
import type { InitialValues } from "@modular-forms/qwik";
import { formAction$, useForm, zodForm$ } from "@modular-forms/qwik";
import { LuGithub as Github, LuChrome as Chrome, LuMail as Mail, LuLock as Lock, LuArrowRight as ArrowRight } from "@qwikest/icons/lucide";
import { useSignIn } from '../plugin@auth';
import { login } from '~/db/auth';
import { ToastType, withToast } from "~/lib/toast";

export const LogIn_Schema = z.object({
  email: z.string().email(),
  password: z.string().min(1),
});
type LogIn_Type = z.infer<typeof LogIn_Schema>;

export const useLogIn_FormLoader = routeLoader$<InitialValues<LogIn_Type>>(
  () => ({
    email: process.env.ADMIN_USER, // TODO: Remove credentials
    password: process.env.ADMIN_PWD, // TODO: Remove credentials
  }),
);

export const useLogIn_FormAction = formAction$<LogIn_Type>(
  async (input, event) => {
    console.log('auth')
    const response = await login(event.platform.env['D1DATA'], { email: input.email, password: input.password })
    console.log('response:', response)
    if (response.code === 200) {
      withToast(event, ToastType.success, 'Login success')
      event.sharedMap.set('session', response.session)
      event.sharedMap.set('user', response.user)
      throw event.redirect(302, '/admin');
    } else {
      withToast(event, ToastType.error, 'Login failed')
      event.fail(response.code, {
        message: response.message,
      })
    }
  },
  zodForm$(LogIn_Schema),
);

export default component$(() => {
  const signIn = useSignIn();
  const [LogIn_Form, { Form, Field }] = useForm<LogIn_Type>({
    loader: useLogIn_FormLoader(),
    action: useLogIn_FormAction(),
    validate: zodForm$(LogIn_Schema),
  });
  return (
    <div class="min-h-screen bg-gradient-to-br from-indigo-100 via-purple-50 to-pink-100 flex items-center justify-center p-4">
      <div class="max-w-md w-full space-y-8 bg-white p-8 rounded-2xl shadow-xl">
        <div class="text-center">
          <h2 class="mt-6 text-3xl font-extrabold text-gray-900">
            Welcome back
          </h2>
          <p class="mt-2 text-sm text-gray-600">
            Sign in to your account to continue
          </p>
        </div>

        <div class="space-y-3">
          <button
            class="w-full flex items-center justify-center gap-3 px-4 py-3 border border-gray-300 rounded-lg shadow-sm bg-white text-gray-700 hover:bg-gray-50 transition duration-150 font-medium"
            onClick$={() => signIn.submit({ providerId: 'github' })}
          >
            <Github class="w-5 h-5" />
            Continue with GitHub
          </button>

          <button
            class="w-full flex items-center justify-center gap-3 px-4 py-3 border border-gray-300 rounded-lg shadow-sm bg-white text-gray-700 hover:bg-gray-50 transition duration-150 font-medium"
            onClick$={() => signIn.submit({ providerId: 'google' })}
          >
            <Chrome class="w-5 h-5 text-blue-500" />
            Continue with Google
          </button>
        </div>

        <div class="relative">
          <div class="absolute inset-0 flex items-center">
            <div class="w-full border-t border-gray-300"></div>
          </div>
          <div class="relative flex justify-center text-sm">
            <span class="px-2 bg-white text-gray-500">Or continue with</span>
          </div>
        </div>

        <Form class="mt-8 space-y-6">
          <div class="space-y-4">
            <Field name="email">
              {(field, props) => (

                <div>
                  <label for="email" class="sr-only">
                    Email address
                  </label>
                  <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <Mail class="h-5 w-5 text-gray-400" />
                    </div>
                    <input {...props} type="email" value={field.value}
                      required
                      autoComplete="email"
                      class="block w-full pl-10 pr-3 py-3 border text-gray-400 border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                      placeholder="Email address"
                    />
                    {field.error && <div>{field.error}</div>}
                  </div>
                </div>
              )}
            </Field>

            <Field name="password">
              {(field, props) => (
                <div>
                  <label for="password" class="sr-only">
                    Password
                  </label>
                  <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                      <Lock class="h-5 w-5 text-gray-400" />
                    </div>
                    <input {...props} type="password" value={field.value}
                      required
                      autoComplete="current-password"
                      class="block w-full pl-10 pr-3 py-3 border text-gray-400 border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                      placeholder="Password"
                    />
                    {field.error && <div>{field.error}</div>}
                  </div>
                </div>
              )}
            </Field>
          </div>

          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <input
                id="remember-me"
                name="remember-me"
                type="checkbox"
                class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
              />
              <label for="remember-me" class="ml-2 block text-sm text-gray-900">
                Remember me
              </label>
            </div>

            <div class="text-sm">
              <a href="#" class="font-medium text-indigo-600 hover:text-indigo-500">
                Forgot your password?
              </a>
            </div>
          </div>
          {LogIn_Form.response.message && (
            <p class="text-red-500">{LogIn_Form.response.message}</p>
          )}

          <button
            type="submit"
            class="group relative w-full flex justify-center py-3 px-4 border border-transparent rounded-lg text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 font-medium transition duration-150"
          >
            Sign in
            <ArrowRight class="ml-2 h-5 w-5 group-hover:translate-x-1 transition-transform duration-150" />
          </button>
        </Form>

        <p class="text-center text-sm text-gray-600">
          Don't have an account?{' '}
          <a href="#" class="font-medium text-indigo-600 hover:text-indigo-500">
            Sign up
          </a>
        </p>
      </div>
    </div>
  );
});

export const head: DocumentHead = {
  title: "Welcome to Login Alist Worker",
};
